import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}



/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  console.log('23',routes)
  console.log('循环列表',data)
  data.forEach(item => {
    // alert(JSON.stringify(item))
    let url = item.routing.split('/')
    console.log(url)
    console.log(url[1])
    const menu = {
      path: item.level === 1 ? item.routing : url[url.length],
      component: item.level === 1 ? Layout : () => import('@/views' + item.routing),
      // hidden: true,
      child: [],
      name: item.level == 1 || item.level == 2 ? url[1] : url[url.length],
      meta: { title: item.name, roles: ['admin'] }
    }
    if (item.child) {
      // debugger
      try {
        generaMenu(menu.child, item.child)
      } catch (error){
        console.log('循环路由报错',error)
      }
    }
    // debugger
    routes.push(menu)
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, {roles, hasrouter}) {
    return new Promise(resolve => {
      let accessedRoutes
      console.log('动态路由',hasrouter)
      generaMenu(asyncRoutes,hasrouter)
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
